home *** CD-ROM | disk | FTP | other *** search
Text File | 1990-01-02 | 2.3 KB | 73 lines | [TEXT/GEOL] |
- Item forwarded by ALCABES to CPLUS.APPLE$
-
- Item 9424175 25-Dec-89 14:36
-
- From: D1622 Nerdworks, Dan Weston,PRT
-
- To: MADA.EUROPE MacApp Dev Assoc Europe, E Carrasco
-
- cc: CPLUS.DEV$ C++ Interest List--Developers
-
- Sub: Re: ?Initializing a static…
-
- I ran into the same sort of confusion with static member initialization myself
- just last week. The problem is that static members are not really members at
- all, rather, they are treated, storage-wise, like regular variables. Take a
- look at the example below: It has one static member and one regular member.
-
- class TFoo {
- private:
- static long fSize; // variable shared by all instances of the class
- // acessible from any method of the class
- long otherSize; // Normal member
-
- /* ... */
- public:
- void IFoo(long size);
- /* ... */
- };
-
- void TFoo::IFoo(long size) {
- this->fSize = size; // kaboom!......why???
- this->otherSize = size;
- }
-
-
- Now look at the intermediate code (edited somewhat) that is generated when you
- compile the code shown above: My extra comments are preceeded by //****
-
-
- //**** note that fSize is not in TFoo struct declaration
- struct TFoo { /* sizeof TFoo == 4 */
- long otherSize;
- };
-
- //**** fSize is declared as extern, just like a global variable
- extern long fSize__4TFoo;
-
-
- //**** definition of IFoo member function
- void IFoo__4TFooFl(register struct TFoo *this, long size){
- fSize__4TFoo= size; //**** accessed like a global
- this-> otherSize= size; //**** accessed like a member
- }
-
-
- You can see that the static member is not really a member of the TFoo struct.
- Static members are actually just like global variables with limited lexical
- access. You can also see that C++ does not automatically allocate space for
- the static member, as evidenced by the 'extern' declaration. It is up to you
- to define space for the static member with a definition/initialization
- statement, such as
-
- long TFoo::fSize = 2;
-
- I define and intialize static members in the same place that I define and
- initialize global variables for a file.
-
- Hope this is helpful.
-
- Dan Weston
- Nerdworks, D1622
-
-